<template>
  <div class="box">
    <!--    人员列表-->
    <div class="box_right">
      <ProTable
          ref="proTable"
          :columns="columns"
          :data-callback="dataCallback"
          :init-param="initParam"
          :request-api="getTableList"
          :selection="true"
          :toolButton="false"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <div v-if="isType" class="header-button-lf">
            <el-button type="primary" @click="openSelectMember">添加</el-button>

            <el-button :disabled="!scope.isSelected" style="color: #606266;" @click="resetPass(scope.selectedListIds)">
              移除
            </el-button>
            <el-button :disabled="!scope.isSelected" style="color: #606266;" @click="openSelectRole">转移
            </el-button>

          </div>
          <div v-else class="header-button-lf">
            <el-button type="primary" @click="openDrawer('新增')">导出</el-button>
          </div>

          <div class="header-button-ri">
            <el-input
                v-model="keywords"
                class="inline-block"
                placeholder="请输入用户账号、用户姓名检索（模糊检索）"
                style="width: 304px"></el-input>
            <el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
            <el-button icon="Search" type="primary" @click="handleSearch">重置</el-button>
          </div>
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <template #createTimeHeader="scope">
        <span class="inline-block">
          <span class="flx-align-center">
            <span>{{ scope.column.label }}</span>
            <span class="flx-align-center ml-10">
              <el-icon @click.stop="handleClickCalendar"><Calendar/></el-icon>
              <el-date-picker
                  ref="timePick"
                  v-model="times"
                  class="time-pick"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  range-separator="至"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  @change="changeTimePick"
              >
              </el-date-picker>
            </span>
          </span>
        </span>
        </template>
        <!-- 自定义内容 -->
        <template #createTime="scope">
          <el-button link type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
            {{ scope.row.createTime }}
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <span style="color: #3370FF" @click="openDrawer('编辑', scope.row)">编辑</span>

        </template>
      </ProTable>
      <!--      新增编辑用户弹窗-->
      <addUesrs v-if="addUesrsList.visble" :datas="addUesrsList" @back="addUesrsList.visble=false"/>
      <ImportExcel ref="dialogRef"/>
      <el-dialog
          v-model="dialogVisible"
          :before-close="handleClose"
          title="注销用户"
          width="500"
      >
        <div style="margin-bottom: 4px;color: #303133;">
          是否确定注销用户？
        </div>
        <div style="margin-bottom: 4px;color: #303133;">
          注销用户前请将该用户所有信息转移至其他用户
        </div>
        <div>
          <el-select
              v-model="value"
              placeholder="请选择用户"
              style="width: 280px"
          >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogVisible = false">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 选人组件 -->
      <zc-select-member
          v-if="showSelectMember"
          :multiple="true"
          title="选择成员"
          @close="showSelectMember = false"
          @selectMember="selectMember"
      ></zc-select-member>
      <!-- 选择角色 -->
      <zc-select-role
          v-if="showSelectRole"
          :multiple="true"
          title="选择角色"
          @close="showSelectRole = false"
          @selectRole="selectRole"
      ></zc-select-role>
    </div>
  </div>
</template>
<script lang="tsx" name="userListModel" setup>
import {reactive, ref} from "vue";
import {useRouter} from "vue-router";
import {User} from "@/api/interface";
import {useHandleData} from "@/hooks/useHandleData";
import {useAuthButtons} from "@/hooks/useAuthButtons";
import {ElMessage} from "element-plus";
import addUesrs from "./model/addUesrs.vue";
import {ColumnProps, ProTableInstance} from "@/components/ProTable/interface";
import {Calendar} from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ZcSelectRole from "@/components/ZcSelectRole/index.vue";
import ZcSelectMember from "@/components/ZcSelectMember/index.vue";
import {
  changeUserStatus,
  deleteUser,
  getUserGender,
  getUserList,
  getUserStatus,
  resetUserPassWord
} from "@/api/modules/user";

//选择用户
// 是否显示选人组件
const showSelectMember = ref(false);

// 打开选择人员组件
const openSelectMember = () => {
  showSelectMember.value = true;
};
// 选择人员返回的数据
const selectMember = data => {
  console.log(data);
};

// 选择角色
// 是否显示选择角色
const showSelectRole = ref(false);

// 打开选择角色组件
const openSelectRole = () => {
  showSelectRole.value = true;
};
// 选择角色返回的数据
const selectRole = data => {
  showSelectRole.value = false
  console.log(data);
};
// 注销弹窗
const dialogVisible = ref(false)
const handleClose = (done: () => void) => {
  dialogVisible.value = false
}
const deregister = (ids) => {
  dialogVisible.value = true
}
const value = ref('')

const options = [
  {
    value: 'Option1',
    label: 'Option1',
  },
  {
    value: 'Option2',
    label: 'Option2',
  },
  {
    value: 'Option3',
    label: 'Option3',
  },
  {
    value: 'Option4',
    label: 'Option4',
  },
  {
    value: 'Option5',
    label: 'Option5',
  },
]
// 新增编辑用户
const addUesrsList = ref({
  visble: false,
  forms: {
    title: '',
  }
})

// 判断是否已注销用户
const isType = ref(true)

const router = useRouter();


// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  type: 1,
  keywords: ""
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getUserList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const {BUTTONS} = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
// const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
//   return (
//     <span class="inline-block">
//       <span class="flx-align-center">
//         {scope.column.label}
//         <el-icon
//           class="ml-10"
//           onClick={e => {
//             e.stopPropagation();
//           }}
//         >
//           <Calendar />
//         </el-icon>
//       </span>
//     </span>
//   );
// };

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  {type: "selection", fixed: "left", align: "center", width: 48},
  {
    prop: "username",
    label: "用户账号",
    minWidth: 178
  },
  {
    prop: "username",
    label: "用户姓名",
    minWidth: 122
  },
  {prop: "email", label: "联系方式", minWidth: 146},

  {
    minWidth: 178,
    prop: "gender",
    label: "角色",
    // 字典数据（本地数据）
    // enum: genderType,
    // 字典请求不带参数
    enum: getUserGender,
    // 字典请求携带参数
    // enum: () => getUserGender({ id: 1 }),
    fieldNames: {label: "genderLabel", value: "genderValue"},

    // 是否多选  默认多选
    filterMultiple: false,
    filters: [
      {text: "男", value: "1"},
      {text: "女", value: "2"}
    ],
    filterMethod: (value, row) => {
      return row.gender == value;
    }
  },
  {
    minWidth: 146,
    prop: "gender",
    label: "部门",
    // 字典数据（本地数据）
    // enum: genderType,
    // 字典请求不带参数
    enum: getUserGender,
    // 字典请求携带参数
    // enum: () => getUserGender({ id: 1 }),
    fieldNames: {label: "genderLabel", value: "genderValue"},

    // 是否多选  默认多选
    filterMultiple: false,
    filters: [
      {text: "男", value: "1"},
      {text: "女", value: "2"}
    ],
    filterMethod: (value, row) => {
      return row.gender == value;
    }
  },
  {
    minWidth: 135,
    prop: "gender",
    label: "负责部门",
    // 字典数据（本地数据）
    // enum: genderType,
    // 字典请求不带参数
    enum: getUserGender,
    // 字典请求携带参数
    // enum: () => getUserGender({ id: 1 }),
    fieldNames: {label: "genderLabel", value: "genderValue"},

    // 是否多选  默认多选
    filterMultiple: false,
    filters: [
      {text: "男", value: "1"},
      {text: "女", value: "2"}
    ],
    filterMethod: (value, row) => {
      return row.gender == value;
    }
  },
  {
    minWidth: 96,
    prop: "status",
    label: "状态",
    enum: getUserStatus,
    render: scope => {
      return (
          <>
            {BUTTONS.value.status ? (
                <el-switch
                    model-value={scope.row.status}
                    active-text={scope.row.status ? "启用" : "禁用"}
                    active-value={1}
                    inactive-value={0}
                    onClick={() => changeStatus(scope.row)}
                />
            ) : (
                <el-tag type={scope.row.status ? "success" : "danger"}>{scope.row.status ? "启用" : "禁用"}</el-tag>
            )}
          </>
      );
    }
  },
  {
    prop: "createTime",
    label: "创建时间",
    sortable: true,
    minWidth: 128
  },
  {prop: "operation", label: "操作", fixed: "right", minWidth: 80}
]);
// 移除
const resetPass = async (ids) => {
  await useHandleData(resetUserPassWord, {id: ids}, `是否将该用户从XXX角色中移除？`);
  proTable.value?.getTableList();
};

// 删除
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteUser, {id: [params.id]}, `删除【${params.username}】用户`);
  proTable.value?.getTableList();
};

// 批量删除
const batchDelete = async (id: string[]) => {
  await useHandleData(deleteUser, {id}, "删除所选用户信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};


// 开关启用
const changeStatus = async (row: User.ResUserList) => {
  await useHandleData(changeUserStatus, {id: row.id, status: row.status == 1 ? 0 : 1}, `切换【${row.username}】用户状态`);
  proTable.value?.getTableList();
};

const openDrawer = (title, row) => {
  addUesrsList.value.visble = true
  addUesrsList.value.forms.title = title
};

// 搜索关键词
const keywords = ref("");

// 选择时间
const times = ref([]);
const timePick = ref();
const handleClickCalendar = () => {
  timePick.value.focus();
};

const changeTimePick = () => {
  console.log(times.value);
};
// 查询
const handleSearch = () => {
  initParam.keywords = keywords.value;
};


const input = ref("")
//  查询部门
const departmentSearch = () => {
  console.log('部门搜索')
}

interface Tree {
  label: string
  children?: Tree[]
}

const handleNodeClick = (data: Tree) => {
  console.log(data)
}

const data: Tree[] = [
  {
    label: '菩勤责任公司',
    children: [
      {
        label: '菩勤枣庄',
        children: [
          {
            label: '商标',
          },
        ],
      },
    ],
  },

]

const defaultProps = {
  children: 'children',
  label: 'label',
}
</script>
<style lang="scss" scoped>
:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: rgba(31, 97, 243, 0.10);
  color: rgba(51, 112, 255, 1);
}


.box {
  display: flex;
  width: 100%;

  .box_left {
    padding: 12px;
    margin-right: 12px;
    width: 296px;
    height: 798px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    position: relative;

    .box_left_input {
      display: flex;
      margin-bottom: 14px;
    }

    .box_left_but {
      position: absolute;
      bottom: 12px;

      .box_left_buta {
        color: #606266;
        width: 296px;
      }

      .box_left_butb {
        color: #3370FF;
        width: 296px;
        border: 1px solid #3370FF;
      }

    }

  }

  .box_right {
    padding: 12px;
    min-width: 600px;
    flex: 1;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
  }
}
</style>
